package com.qinglei.recoup.longconn.handler;

import com.qinglei.recoup.longconn.constant.LongConnConstant;
import com.qinglei.recoup.longconn.entity.Message;
import com.qinglei.recoup.longconn.entity.UploadDataEvent;
import com.qinglei.recoup.longconn.utils.ProtocolUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
@ChannelHandler.Sharable
public class UploadDataHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Channel channel = ctx.channel();
        Message message = (Message) msg;
        String funcCode = message.getFuncCode();
        if (LongConnConstant.FUNC_UP_USER_DATA.equals(funcCode)){
            // 上传用户数据
            // 解码用户上传数据
//            message.setBody(ProtocolUtils.decodeUserDataBody((byte[]) message.getBody()));
            log.debug("receive user data from {} message: {}", channel.remoteAddress(), message);
            applicationEventPublisher.publishEvent(new UploadDataEvent(message));
        }else if (LongConnConstant.FUNC_UP_GRAYSCALE_DATA.equals(funcCode)){
            // 上传灰度数据
            // 解码用户上传数据
//            message.setBody(GrayScaleDataBody.decodeData((byte[]) message.getBody()));
            log.debug("receive gray-scale data from {} message: {}", channel.remoteAddress(), message);
            applicationEventPublisher.publishEvent(new UploadDataEvent(message));
        }
        else {
            log.info("other func:{}", funcCode);
            ctx.fireChannelRead(msg);
        }
    }

}
